//
//  DrawerDialog.swift
//  DemoUI
//
//  Created by 白瑾浩 on 2022/12/1.
//

import Foundation
import UIKit
class DrawerDialog{
    var mUIAlertController:UIAlertController?
    init(title: String, message:String = "",style:UIAlertController.Style = .actionSheet, handle:((UIAlertController)->Void)? = nil  ){
        
        mUIAlertController  =  UIAlertController(title: title, message: message, preferredStyle: style)
         
//        let subview = mUIAlertController?.view.subviews.first as? UIView
//        let alertContentView = subview!.subviews.first! as UIView
//        alertContentView.backgroundColor = UIColor.white
        
        if handle != nil {
            handle!( mUIAlertController! )
        }
        
        SceneDelegate.window?.rootViewController?.present(mUIAlertController!, animated: true,completion: nil )
        
    }
    @discardableResult
    func addAlertAction(title: String, style : UIAlertAction.Style = .default, textColor:UIColor? = nil, bgColor:UIColor = UIColor.darkGray, handler: ((UIAlertAction) -> Void)? = nil, returnAction:((UIAlertAction) -> Void)? = nil )->DrawerDialog{
        let action = UIAlertAction(title: title, style: style ) { (action) in
            if handler != nil{
                handler!( action )
            }
        }
    
        if returnAction != nil {
            returnAction!( action )
        }
        if textColor != nil {
            action.setTextColor(textColor!)
        }
        mUIAlertController?.addAction( action )
        return self
    }
    
    
}

extension UIAlertAction{
    
    static var propertyNames: [String] {
        var outCount: UInt32 = 0
        guard let ivars = class_copyIvarList(self, &outCount) else {
            return []
        }
        var result = [String]()
        let count = Int(outCount)
        for i in 0..<count {
            let pro: Ivar = ivars[i]
            guard let ivarName = ivar_getName(pro) else {
                continue
            }
            guard let name = String(utf8String: ivarName) else {
                continue
            }
            result.append(name)
        }
        return result
    }
    
    func isPropertyExisted(_ propertyName: String) -> Bool {
        for name in UIAlertAction.propertyNames {
            if name == propertyName {
                return true
            }
        }
        return false
    }
    
    func setTextColor(_ color: UIColor) {
        let key = "_titleTextColor"
        guard isPropertyExisted(key) else {
            return
        }
        self.setValue(color, forKey: key)
    }
    
    
    
}

